

#include "ContactHandler.h"
#include "../common/ContactException.h"

#include "request/add_contact_request.pb.h"
#include "response/add_contact_response.pb.h"
#include "response/base_response.pb.h"
#include "request/del_contact_request.pb.h"
#include "response/del_contact_response.pb.h"
#include "request/find_one_contact_request.pb.h"
#include "response/find_one_contact_response.pb.h"

#include "request/find_all_contact_request.pb.h"
#include "response/find_all_contact_response.pb.h"

#include "../common/Utils.h"


void ContactHandler::handleAddContact(const httplib::Request& req, httplib::Response& res)
{
    try
    {
        // 1. 接收并解析请求
        add_contact_req::AddContactRequest request;
        if (!request.ParseFromString(req.body))
        {
            // Protobuf 解析失败
            add_contact_resp::AddContactResponse resp;
            resp.mutable_base_resp()->set_success(false);
            resp.mutable_base_resp()->set_error_desc("请求反序列化失败!");

            std::string resp_str;
            resp.SerializeToString(&resp_str);

            res.status = 400; // Bad Request
            res.set_content(resp_str, "application/protobuf");
            return;
        }

         // 生成唯一的 UID
        std::string uid = Utils::generate_uuid();

        // 将联系人数据保存到文件
        ContactStorage::saveContact(request,uid);

        // 3. 构建响应
        add_contact_resp::AddContactResponse resp;
        resp.mutable_base_resp()->set_success(true);
        resp.mutable_base_resp()->set_error_desc("");  // 没有错误
        resp.set_uid(uid);

        // 4. 序列化响应
        std::string resp_str;
        if (!resp.SerializeToString(&resp_str))
        {
            res.status = 500; // Internal Server Error
            res.set_content("序列化响应失败", "text/plain");
            return;
        }

        res.status = 200; // OK
        res.set_content(resp_str, "application/protobuf");
    }
    catch (const ContactException& e)
    {
        // 5. 自定义异常
        add_contact_resp::AddContactResponse resp;
        resp.mutable_base_resp()->set_success(false);
        resp.mutable_base_resp()->set_error_desc(std::string("业务异常: ") + e.what());

        std::string resp_str;
        resp.SerializeToString(&resp_str);

        res.status = 500; // 业务异常也返回 500
        res.set_content(resp_str, "application/protobuf");
    }
    catch (const std::exception& e)
    {
        // 6. 未知异常兜底
        add_contact_resp::AddContactResponse resp;
        resp.mutable_base_resp()->set_success(false);
        resp.mutable_base_resp()->set_error_desc(std::string("未知异常: ") + e.what());

        std::string resp_str;
        resp.SerializeToString(&resp_str);

        res.status = 500;
        res.set_content(resp_str, "application/protobuf");
    }
}


void ContactHandler::handleDelContact(const httplib::Request& req, httplib::Response& res)
{
    // 1. 解析请求
    del_conctact_req::DelContactRequest request;
    if(!request.ParseFromString(req.body))
    {
        del_contact_resp::BaseResponse resp;
        resp.set_success(false);
        resp.set_error_desc("请求反序列化失败!");
        res.status = 400; // Bad Request

        std::string resp_str;
        resp.SerializeToString(&resp_str);
        res.set_content(resp_str,"application/protobuf");
        return;
    }

    // 2. 执行业务逻辑：删除联系人（根据 uid）
    bool result  = ContactStorage::deleteContact(request.uid());

    // 3. 构建响应
    del_contact_resp::BaseResponse resp;
    if(!result)
    {
        resp.set_success(false);
        resp.set_error_desc("未找到对应的联系人!");
    }
    else 
    {
        resp.set_success(true);
        resp.set_error_desc("");
    }

    // 4. 序列化响应
    std::string resp_str;
    resp.SerializeToString(&resp_str);
    res.status = 200;
    res.set_content(resp_str, "application/protobuf");
}

void ContactHandler::handleFindOneContact(const httplib::Request& req, httplib::Response& res)
{
    // 1. 解析请求
    find_one_contact_req::FindOneContactRequest request;
    if(!request.ParseFromString(req.body))
    {
        find_one_contact_resp::FindOneContactResponse response;
        response.mutable_base_reso()->set_success(false);
        response.mutable_base_reso()->set_error_desc("求反序列化失败!");
        res.status = 400; // Bad Request
        std::string resp_str;
        if(response.SerializeToString(&resp_str))
        {
            DEBUG_LOG("handleFindOneContact 序列号error !");
        }
        res.set_content(resp_str, "application/protobuf");
        return;

    }
    // 2. 执行业务逻辑：查找联系人（根据 姓名）
    add_contact_req::AddContactRequest contact;
    std::string uid;
    bool result  = ContactStorage::findContactByName(request.name(),contact,uid);
 
    // 3. 构建响应 
    find_one_contact_resp::FindOneContactResponse response;
    if(result)
    {
        response.mutable_base_reso()->set_success(true);
        response.mutable_base_reso()->set_error_desc("");

        response.set_uid(uid);
        response.set_name(contact.name());
        response.set_age(contact.age());
        
        for(int i = 0; i < contact.phone_size(); i++)
        {
            response.add_phone(contact.phone(i).number());
        }
    }
    else 
    {
        response.mutable_base_reso()->set_success(false);
        response.mutable_base_reso()->set_error_desc("未找到该联系人!");
    }

    // 4. 序列化响应
    std::string resp_str;
    if(response.SerializeToString(&resp_str))
    res.status = 200;
    res.set_content(resp_str, "application/protobuf");
}


void ContactHandler::handleFindAllContacts(const httplib::Request& req, httplib::Response& res)
{
    std::vector<add_contact_req::AddContactRequest> contacts;
    std::vector<std::string> uids;

    bool ok = ContactStorage::findAllContacts(contacts, uids);

    find_all_contact_resp::FindAllContactResponse response;
    if (!ok)
    {
        response.mutable_base_resp()->set_success(false);
        response.mutable_base_resp()->set_error_desc("没有找到任何联系人！");
    }
    else
    {
        response.mutable_base_resp()->set_success(true);
        response.mutable_base_resp()->set_error_desc("");

        for (size_t i = 0; i < contacts.size(); i++)
        {
            find_all_contact_resp::ContactInfo* info = response.add_contacts();
            info->set_uid(uids[i]);
            info->set_name(contacts[i].name());
            info->set_age(contacts[i].age());
            for (int j = 0; j < contacts[i].phone_size(); j++)
            {
                info->add_phone(contacts[i].phone(j).number());
            }
        }
    }

    std::string resp_str;
    response.SerializeToString(&resp_str);
    res.status = 200;
    res.set_content(resp_str, "application/protobuf");
}
